<template>
    <div>
        <NavHeader />

        <!-- 内容区域 -->
        <div class="content">
            <el-card class="box-card">
                <div class="user_information">
                    <div class="user_img">
                        <div class="user_img_cover">
                            <div class="user_img_img">
                                <img :src="servicePort + userInfo.cover" alt="" />
                                <span class="role">{{ userInfo.role === 'shop' ? '商家' : userInfo.role === 'vip' ? 'VIP' : '用户' }}</span>
                            </div>
                        </div>
                        <div class="user_img_primary_id">
                            {{ userInfo.name || userInfo.primary_id }}
                        </div>
                        <div class="user_img_description">
                            <span>{{ userInfo.nickname || userInfo.name }}</span>
                            <span>
                                {{ userInfo.sex === 'man' ? '男' : '女' }}
                            </span>
                        </div>
                        <div class="user_img_change">
                            <div class="text">
                                <span
                                    v-if="userInfo.role === 'shop'"
                                    @click="gotoRouter('/shop_store')"
                                    >店铺信息</span
                                >
                                <span v-else @click="dialogVisibleBecomeShop = true">成为商家</span>
                            </div>
                            <a @click="manageCar">管理车辆</a>
                        </div>
                    </div>
                    <div class="user_info">
                        <div class="user_info_card">
                            <el-card class="card">
                                <div class="card_item1">我的账户</div>
                                <div class="card_item2">
                                    <div class="card_item2_item">
                                        <p class="text">账户余额</p>
                                        <p class="account">
                                            {{ (userInfo.account || 0).toFixed(2) }}
                                        </p>
                                    </div>
                                    <div class="divider"></div>
                                    <div class="card_item2_item item" @click="gotoRouter('/order')">
                                        <p class="text">我的订单</p>
                                        <p class="account">
                                            {{ userInfo.order_number || 0 }}
                                        </p>
                                    </div>
                                    <div class="divider"></div>
                                    <div class="card_item2_item item" @click="gotoRouter('/cart')">
                                        <p class="text">我的购物车</p>
                                        <p class="account">
                                            {{ userInfo.cart_number || 0 }}
                                        </p>
                                    </div>
                                </div>
                            </el-card>
                        </div>
                    </div>
                </div>

                <div class="service_message">
                    <el-card>
                        <p class="service_message_text">其他服务</p>
                        <div class="service_message_content">
                            <div class="service_message_content_item" @click="editMessage">
                                <i class="iconfont icon-bianji icon-text"></i>
                                <span class="icon-tip">编辑信息</span>
                            </div>
                            <div class="service_message_content_item" @click="accountAdd">
                                <i class="iconfont icon-chongzhi icon-text"></i>
                                <span class="icon-tip">账户充值</span>
                            </div>
                            <div class="service_message_content_item" @click="logout">
                                <i class="iconfont icon-icon_shezhi icon-text"></i>
                                <span class="icon-tip">退出登录</span>
                            </div>
                        </div>
                    </el-card>
                </div>
            </el-card>
        </div>

        <!-- 管理车辆 -->

        <el-drawer v-model="drawer" size="50%">
            <template #header>
                <h4>管理车辆</h4>
            </template>

            <template #default>
                <el-alert style="margin-bottom: 20px" title="最多只能拥有10辆车" type="warning" />
                <el-button style="margin-bottom: 10px" @click="addCar"> + 添加车辆 </el-button>
                <div v-if="carTableData.length !== 0">
                    <el-table :data="carTableData" style="width: 100%" @row-click="handleRowClick">
                        <el-table-column prop="license_plate" label="车牌号" width="180" />
                        <el-table-column prop="brand" label="品牌" width="180" />
                        <el-table-column prop="displacement" label="排量" />
                        <el-table-column prop="shape" label="型号" />
                        <el-table-column prop="status" label="状态">
                            <template #default="{ row }">
                                <div style="display: flex; align-items: center">
                                    <el-tag type="warning" v-if="row.status === '0'">运行中</el-tag>
                                    <el-tag type="primary" v-else-if="row.status === '1'"
                                        >待处理</el-tag
                                    >
                                    <el-tag type="success" v-else>已修好</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div v-else>您还没有车辆，可以新增自己的车辆</div>
            </template>
        </el-drawer>

        <el-dialog v-model="isCarPhotoVisible" title="车辆图片信息" :before-close="() => {
            fileList = []
            isCarPhotoVisible = false
        }">
            <div class="image_list">
                <el-upload
                    v-model:file-list="fileList"
                    multiple
                    name="files"
                    :headers="authorization"
                    :action="servicePort + '/api/upload/doAdds_car'"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                    :before-upload="beforeCarUpload2"
                    :before-remove="(file, fileList) => {
                        if (fileList.length === 1) {
                             ElMessage({
                                message: '至少保留一张图片',
                                type: 'warning'
                            })
                            return false
                        }
                    }"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisiblePic">
                    <img style="width: 100%; height: 100%;" :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </div>
        </el-dialog>

        <!-- 添加车辆 -->
        <el-dialog v-model="dialogVisibleAddCar" title="添加车辆" width="600">
            <el-form
                :model="addCarForm"
                :rules="addCarFormRules"
                ref="addCarFormRef"
                hide-required-asterisk="false"
            >
                <el-form-item label="车牌" prop="license_plate">
                    <el-input
                        placeholder="请输入车牌号"
                        v-model="addCarForm.license_plate"
                    ></el-input>
                </el-form-item>
                <el-form-item label="品牌" prop="brand">
                    <el-input placeholder="请输入车辆品牌" v-model="addCarForm.brand"></el-input>
                </el-form-item>
                <el-form-item label="排量" prop="displacement">
                    <el-input
                        placeholder="请输入车辆排量"
                        v-model="addCarForm.displacement"
                    ></el-input>
                </el-form-item>
                <el-form-item label="型号" prop="shape">
                    <el-input placeholder="请输入车辆型号" v-model="addCarForm.shape"></el-input>
                </el-form-item>
                <el-form-item label="颜色" prop="color">
                    <el-input placeholder="请输入车辆颜色" v-model="addCarForm.color"></el-input>
                </el-form-item>

                <!-- 车辆图片上传 -->
                <el-form-item label="图片" prop="photos">
                    <el-upload
                                multiple
                                name="files"
                                class="avatar-uploader"
                                :action="servicePort + '/api/upload/doAdds_car'"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess2"
                                :before-upload="beforeCarUpload"
                                :headers="authorization"
                            >
                                <img
                                    v-for="item in addCarForm.photos"
                                    :src="servicePort + item?.url"
                                    class="avatar"
                                />
                                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="()=>{
                        dialogVisibleAddCar = false
                        addCarFormRef.resetFields()
                    }">取消</el-button>
                    <el-button type="primary" @click="addCarConfirm"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 成为商家 -->
        <el-dialog v-model="dialogVisibleBecomeShop" title="成为商家" width="500">
            <el-form :model="shopForm" :rules="shopFromRules" ref="shopRef">
                <el-form-item label="店铺名称" prop="shopName">
                    <el-input placeholder="请输入店铺的名称" v-model="shopForm.shopName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="becomeShop"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog
            v-model="dialogVisible"
            title="编辑个人信息"
            width="500"
            :before-close="handleClose"
        >
            <el-form :model="editForm" :rules="rules" ref="editFormRef">
                <el-form-item label="昵&nbsp;&nbsp;&nbsp;称" prop="nickname">
                    <el-input placeholder="请输入昵称" v-model="editForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="性&nbsp;&nbsp;&nbsp;别" prop="sex">
                    <el-select v-model="editForm.sex" placeholder="选择性别">
                        <el-option label="男" value="man" />
                        <el-option label="女" value="female" />
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input placeholder="请输入内容" v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="描&nbsp;&nbsp;&nbsp;述" prop="description">
                    <el-input
                        type="textarea"
                        placeholder="请输入描述内容"
                        v-model="editForm.description"
                    ></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="confirmation"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserInfo } from '@/api'
import { updateUserDetail, userBecomeShop, getCarInfo, addCarPhoto, addCarInfo, getCarById, removeCarPhoto} from '@/api/home'
import message from '@/utils/message'
import { servicePort } from '@/request'
import { ElMessage, ElMessageBox, checkboxGroupEmits, valueEquals } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const dialogVisible = ref(false)
const dialogVisiblePic = ref(false)
const dialogVisibleBecomeShop = ref(false)
const dialogVisibleAddCar = ref(false)
const editFormRef = ref()
const shopRef = ref()
const addCarFormRef = ref()
const drawer = ref(false)
const isCarPhotoVisible = ref(false)
const imageUrl = ref('')
const userInfo = reactive({})
const router = useRouter()
const editForm = reactive({
    nickname: '',
    sex: '',
    phone: '',
    description: ''
})
const shopForm = reactive({
    shopName: ''
})

const fileList = ref([])
const dialogImageUrl = ref('')

// 添加车辆
const addCarForm = reactive({
    license_plate: '',
    brand: '',
    displacement: '',
    shape: '',
    color: '',
    photos: [] // 车辆图片
})
const authorization = {
    authorization: 'Bearer ' + localStorage.getItem('vehicle_web_token') || ''
}

const carTableData = reactive([])
let carPhotos = reactive([])
const curCarId = ref('')

const validatePass = (rule, value, callback) => {
    let reg = /^1[3-9]\d{9}$/
    if (value === '') {
        callback(new Error('手机号不能为空'))
    } else if (!reg.test(value)) {
        callback(new Error('号码不符合规则'))
    } else {
        callback()
    }
}

const validatePass1 = (rule, value, callback) => {
    let reg = /^[\u4e00-\u9fa5][A-Z][A-HJ-NP-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
    if (value === '') {
        callback(new Error('车牌号不能为空'))
    } else if (reg.test(value)) {
        callback(new Error('请填写正确的车牌格式'))
    } else {
        callback()
    }
}

// 检验车辆的图片是否上传
const validatePass2 = (rule, value, callback) => {
    if (addCarForm.photos.length === 0) {
        callback(new Error('必须上传车辆图片'))
    } else {
        callback()
    }
}

const rules = reactive({
    nickname: [{ min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }],
    phone: [{ validator: validatePass, trigger: 'blur' }]
})

const shopFromRules = reactive({
    shopName: [
        { required: true, message: '店铺名称不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ]
})

const addCarFormRules = reactive({
    license_plate: [{ validator: validatePass1, trigger: 'blur' }],
    brand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
    displacement: [{ required: true, message: '排量不能为空', trigger: 'blur' }],
    shape: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
    color: [{ required: true, message: '颜色不能为空', trigger: 'blur' }],
    photos: [{ validator: validatePass2, trigger: 'blur' }] 
})

const init = async () => {
    const res = await getUserInfo()
    if (res.status !== 200) return message.error('获取数据失败')
    Object.assign(userInfo, res.data.userInfo)
    editForm.nickname = userInfo.nickname
    editForm.sex = userInfo.sex
    editForm.phone = userInfo.phone
    editForm.description = userInfo.description
}

init()

const gotoRouter = (path) => {
    if (!userInfo) {
        router.push('/login')
        return
    }
    router.push(path)
}

//  账户充值
const accountAdd = () => {
    ElMessageBox.prompt('请输入充值金额', '账户充值', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+(\.\d{1,2})?$/,
        inputErrorMessage: '请输入正确的金额'
    })
        .then(async ({ value }) => {
            const res = await updateUserDetail({ account: value })
            if (res.status !== 200) {
                return ElMessage.error('账户充值失败')
            }
            init()
            ElMessage({
                type: 'success',
                message: '充值成功'
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消充值'
            })
        })
}

const editMessage = () => {
    editForm.nickname = userInfo.nickname
    editForm.sex = userInfo.sex
    editForm.phone = userInfo.phone
    editForm.description = userInfo.description
    dialogVisible.value = true
}

const handleClose = () => {
    dialogVisible.value = false
    editFormRef.value.resetFields()
}

const cancel = () => {
    dialogVisibleBecomeShop.value = false
    shopRef.value.resetFields()
}

// 编辑信息
const confirmation = () => {
    editFormRef.value.validate(async (valid) => {
        if (valid) {
            const res = await updateUserDetail(editForm)
            if (res.status !== 200)
                return ElMessage({
                    message: '修改失败',
                    type: 'error'
                })
            init()
            dialogVisible.value = false
        }
    })
}

// 成为商家
const becomeShop =  () => {
    shopRef.value.validate(async (valid) => {
        if (valid) {
            const res = await userBecomeShop(shopForm)
            ElMessage({
                message: '成为商家成功',
                type: 'success'
            })
            init()
            dialogVisibleBecomeShop.value = false
        }
    })
}

// 管理车辆
const manageCar = async () => {
    drawer.value = true

    const res = await getCarInfo()
    if (res.status !== 200)
        return ElMessage({
            type: 'error',
            message: '获取数据失败'
        })
    Object.assign(carTableData, res.data)
}

// 行点击事件=======
const handleRowClick = async ({ id, photos }) => {
    const {data} = await getCarById(id)
    fileList.value = data.photos.map(photo => ({url: servicePort + photo.url, id: photo.id}))
    curCarId.value = id
    isCarPhotoVisible.value = true
}

const handlePictureCardPreview= (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisiblePic.value = true
}

// 移除车辆图片
const handleRemove = async (uploadFile, uploadFiles) => {
    const res = await removeCarPhoto(uploadFile.id)
    if (res.status !== 200) return ElMessage.error('移除图片失败')
    return ElMessage.success('移除图片成功')
}

// 单独上传图片成功后的回调函数
const handleSuccess = async (response, uploadFile) => {
    if (response.status === 200) {
        const {data} = await addCarPhoto(curCarId.value, response.data.list || [])
        if (data.code === 900) {
            ElMessage({
                message: '上传成功',
                type: 'success'
            })
            const res = await getCarById(curCarId.value)
            fileList.value = res.data.photos.map(photo => ({url: servicePort + photo.url, id: photo.id}))
        }
    }
}

// 新增车辆时上传图片成功时的回调函数
const handleAvatarSuccess2 = (response, uploadFile) => {
    addCarForm.photos = [...addCarForm.photos, ...response.data.list]
}

const beforeCarUpload = (rawFile) => {
    if (addCarForm.photos.length >= 5) {
        ElMessage({
            message: '最多只能上传五张图片',
            type: 'error'
        })
        return false
    }
    if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error(`图片格式错误 ${rawFile.type}`)
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

const beforeCarUpload2 = (rawFile) => {
    if (fileList.length >= 5) {
        ElMessage({
            message: '最多只能上传五张图片',
            type: 'error'
        })
        return false
    }
    if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error(`图片格式错误 ${rawFile.type}`)
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

// 添加车辆
const addCar = () => {
    if (carTableData.length >= 10) {
        return ElMessage.warning('车辆数量不能超过 10 辆')
    }
    addCarForm.brand = ''
    addCarForm.displacement = ''
    addCarForm.photos = []
    addCarForm.license_plate = ''
    addCarForm.shape = ''
    addCarForm.color = ''
    dialogVisibleAddCar.value = true
}

const addCarConfirm = () => {
    addCarFormRef.value.validate(async (valid) => {
        if (valid) {
            const res = await addCarInfo(addCarForm)
            if (res.status !== 200)
                return ElMessage({
                    message: '添加失败',
                    type: 'error'
                })
            ElMessage({
                message: '添加成功',
                type: 'success'
            })
            dialogVisibleAddCar.value = false
            const result = await getCarInfo()

            Object.assign(carTableData, result.data)
        }
    })
}

const upLoadPhoto = async () => {}

const logout = () => {
    ElMessageBox.confirm('是否确定退出登录', '⏏️  退出登录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            router.push('/login')
            localStorage.removeItem('vehicle_web_token')
            localStorage.removeItem('vehicle_web_userInfo')
            localStorage.removeItem('userInfo')
            ElMessage({
                type: 'success',
                message: '退出登录成功'
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消退出'
            })
        })
}
</script>

<style lang="scss" scoped>
.content {
    padding: 10px 260px;
    .box-card {
        padding: 0;
        .user_information {
            padding: 20px 0;
            height: 260px;
            display: flex;
            .user_img {
                width: 300px;
                height: 100%;
                background-color: red;
                display: flex;
                flex-direction: column;

                .user_img_cover {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 100%;
                    height: 120px;
                    color: #343434;
                    font-size: 12px;
                    .user_img_img {
                        position: relative;
                        width: 100px;
                        height: 100px;
                        margin: 0 auto;
                        border-radius: 50%;
                        padding: 10px;
                        img {
                            width: 100%;
                            height: 100%;
                            border-radius: 50%;
                            border: 1px solid #ccc;
                        }
                        .role {
                            display: inline-block;
                            position: absolute;
                            text-align: center;
                            width: 50px;
                            height: 18px;
                            line-height: 18px;
                            z-index: 10;
                            background-color: #fff;
                            border-radius: 10px;
                            top: 75px;
                            right: 24px;
                        }
                    }
                }

                .user_img_primary_id {
                    width: 100%;
                    font: 700 18px / 20px Arial;
                    color: #fff;
                    text-align: center;
                    line-height: 30px;
                }
                .user_img_description {
                    width: 100%;
                    text-align: center;
                    line-height: 30px;
                    span {
                        padding: 0 10px;
                        border: 1px solid #fff;
                        color: #fff;
                        display: inline-block;
                        margin: 0 5px;
                        height: 22px;
                        line-height: 22px;
                        border-radius: 12px;
                    }
                }
                .user_img_change {
                    background-color: black;
                    margin-top: 10px;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    .text {
                        margin-right: 10px;
                        color: #f4ca3a;
                        cursor: pointer;
                        em {
                            font-weight: 700;
                            display: block;
                        }
                    }
                    a {
                        padding: 0 10px;
                        height: 26px;
                        line-height: 26px;
                        border-radius: 14px;
                        background-color: #f4ca3a;
                        color: #232331;
                        font-weight: 700;
                        text-align: center;
                        cursor: pointer;
                    }
                }
            }
            .user_info {
                width: 100%;
                height: 100%;
                padding: 10px 0 10px 0;
                .user_info_card {
                    border: 1px solid #ccc;
                    padding: 20px;
                    height: 100%;
                    .card {
                        .card_item1 {
                            font-size: 18px;
                            font-weight: 700;
                            padding-bottom: 10px;
                            border-bottom: 1px solid #ccc;
                        }
                        .card_item2 {
                            margin-top: 20px;
                            display: flex;
                            justify-content: space-around;
                            .divider {
                                width: 1px;
                                height: 50px;
                                border: 1px solid #ccc;
                            }
                            .item {
                                cursor: pointer;
                                &:hover {
                                    color: red;
                                }
                            }

                            .card_item2_item {
                                width: 200px;
                                display: flex;
                                align-items: center;
                                flex-direction: column;
                                padding: 10px 0;
                                .text {
                                    margin-bottom: 10px;
                                    font-size: 16px;
                                    font-weight: 700;
                                }
                                .account {
                                    font-size: 14px;
                                }
                            }
                        }
                    }
                }
            }
        }

        .service_message {
            padding: 20px 80px;
            .service_message_text {
                font-size: 18px;
                font-weight: 700;
                padding-bottom: 10px;
                border-bottom: 1px solid #ccc;
            }
            .service_message_content {
                margin-top: 20px;
                display: flex;
                .service_message_content_item {
                    cursor: pointer;
                    flex: 1;
                    text-align: center;
                    display: flex;
                    flex-direction: column;
                    .icon-text {
                        font-size: 34px;
                    }
                    .icon-tip {
                        margin-top: 20px;
                    }
                    &:hover {
                        color: red;
                    }
                }
            }
        }
    }
    .image_box {
        width: 300px;
        margin: 0 auto;
    }
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}

.avatar-uploader .avatar {
        width: 80px;
        height: 80px;
        display: block;
    }


</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}


</style>